﻿#region 文件信息

/*----------------------------------------------------------------
//
// 文件名称：
// 文件功能描述：
// 设计要求：
//
// 文 件 名：    RegisterRPC
// 创建者：      杨程
// 创建日期：	    2023/1/6 17:22:03

//----------------------------------------------------------------*/

#endregion

namespace Vampirewal.Admin.Server.RpcServices;

/// <summary>
/// TouchSocket服务实现
/// </summary>
public partial class TouchRpcService : ObservableObject, ITouchRpcService
{
    public TouchRpcService()
    {
        var service = new HttpTouchRpcService();

        var config = new TouchSocketConfig()//配置
                         .UsePlugin()
                         .SetListenIPHosts(new IPHost[] { new IPHost(7790) })
                         .SetReceiveType(ReceiveType.Auto)
                         .ConfigureContainer(a =>
                         {
                             //a.SetLogger<LoggerGroup<ConsoleLogger, FileLogger>>();//注册一个日志组
                         })
                         .ConfigureRpcStore(a =>
                         {
                             //a.RegisterServer<MyRpcServer>();//注册服务
                             a.RegisterAllServer();

#if DEBUG
                             //只有不是生产环境才进行生成RpcMethod.cs文件
                             if (VampirewalCoreContext.GetInstance().GetOptionsValue<bool>("EnvironmentOptions:IsGenerateRpcMethod"))
                             {
                                 a.GenerateApiDocument();//生成一个简单的接口文档
                                 a.GenerateRpcMethodFile();
                             }
#endif
                         })
                         .ConfigurePlugins(a =>
                         {
                             a.Add<JsonRpcParserPlugin>().SetJsonRpcUrl("/jsonrpc");//tcp中路由路径无效

                             if (!Directory.Exists($"{AppDomain.CurrentDomain.BaseDirectory}html"))
                             {
                                 Directory.CreateDirectory($"{AppDomain.CurrentDomain.BaseDirectory}html");
                             }

                             //a.Add<HttpStaticPagePlugin>().AddFolder($"{AppDomain.CurrentDomain.BaseDirectory}Html");//添加静态页面文件夹
                             a.Add<HttpStaticPagePlugin>().AddFolder($"../html");//添加静态页面文件夹

                             a.Add<TouchRpcActionPlugin<HttpTouchRpcClient>>()
                              .SetFileTransfering((client, e) =>
                              {
                                  string? operation = e.Metadata["Operation"];

                                  if (!string.IsNullOrEmpty(operation))
                                  {
                                      if (operation == "上传附件")
                                      {
                                      }
                                      else if (operation == "发布新版本")
                                      {
                                      }
                                      else if (operation == "下载新版本")
                                      {
                                      }
                                  }
                              })
                              .SetFileTransfered((client, e) =>
                              {
                                  if (e.Result.ResultCode == ResultCode.Success)
                                  {
                                  }
                              });

                             a.Add<ClientMutualCallPlugin>();
                         })
                         .SetMaxCount(10000)
                         //.SetThreadCount(100)
                         .SetRootPath($"{AppDomain.CurrentDomain.BaseDirectory}Files")
                         .SetVerifyToken("VampirewalAdmin");

        service.Connected += (HttpTouchRpcSocketClient client, TouchSocketEventArgs e) =>
        {
        };

        service.Connecting += (HttpTouchRpcSocketClient client, OperationEventArgs e) =>
        {
        };

        service.IDChanged += (client, e) =>
        {
            try
            {
                #region ID变化之后，修改用户的在线状态

                var user = JsonConvert.DeserializeObject<Sys_User>(e.NewID);

                user.IsOnline = true;

                #endregion
            }
            catch
            {
            }
        };

        service.Disconnected += (HttpTouchRpcSocketClient client, DisconnectEventArgs e) =>
        {
            try
            {
                var user = JsonConvert.DeserializeObject<Sys_User>(client.ID);

                user.IsOnline = false;

                VampirewalCoreEventBusManager.GetInstance().Publish("UpdateUserLoginState", user);
                //断线之后，移除上下文中的用户数据
                VampirewalCoreContext.GetInstance().RemoveContext(user.BillId);
                VampirewalCoreContext.GetInstance().RemoveContext($"{user.BillId}-httpclient");
            }
            catch
            {
            }
        };

        TouchRpc = service.Setup(config);
    }

    private IService TouchRpc { get; set; }

    private bool _IsStart;

    public bool IsStart
    {
        get
        {
            return _IsStart;
        }
        set
        {
            _IsStart = value;
            OnPropertyChanged();
        }
    }

    public void Start()
    {
        try
        {
            TouchRpc.Start();
            IsStart = true;
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    public void Stop()
    {
        try
        {
            TouchRpc.Stop();
            IsStart = false;
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}